package network.server;

import graphics.Shape;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * An object of this class is used to store the shape data received from clients
 * on the server. The list of shape data is time controlled which means all the
 * data is order by the timestamp when it was received by the server.
 * 
 * @author Jie Zhao(288654)
 * 
 */
public class ControlledShapesData {
	private List<Data> data = Collections
			.synchronizedList(new ArrayList<Data>());

	private static ControlledShapesData instance = new ControlledShapesData();

	private ControlledShapesData() {
	}

	public static ControlledShapesData getInstance() {
		return instance;
	}

	public void addData(Shape s) {
		synchronized (data) {
			if (s != null) {
				Data d = new Data();
				d.timestamp = System.currentTimeMillis();
				d.shape = s;
				data.add(d);
			}
		}
	}

	public void clear() {
		synchronized (data) {
			data.clear();
		}
	}

	public void sort() {
		synchronized (data) {
			Collections.sort(data);
		}
	}

	private class Data implements Comparable<Data> {
		public long timestamp = 0;
		public Shape shape;

		@Override
		public int compareTo(Data o) {
			// TODO Auto-generated method stub
			return (int) (this.timestamp - o.timestamp);
		}
	}

	public List<Shape> getShapeData() {
		List<Shape> l = new ArrayList<Shape>();
		synchronized (data) {
			sort();
			for (Data d : data) {
				l.add(d.shape);
			}
		}
		return l;
	}
}
